/**
 * 与Java Base64.DEFAULT完全兼容的解码函数
 * @param {string} base64Str - 输入的Base64字符串
 * @returns {Uint8Array} - 转换后的字节数组
 */
export function javaCompatibleBase64Decode(base64Str) {
  // 移除可能的前缀
  const pureBase64 = base64Str.replace(/^data:[^;]+;base64,/, '');
  
  // 处理URL安全变体
  let normalizedBase64 = pureBase64
    .replace(/-/g, '+')
    .replace(/_/g, '/');
  
  // 处理填充
  const paddingLength = normalizedBase64.length % 4;
  if (paddingLength) {
    normalizedBase64 += '='.repeat(4 - paddingLength);
  }
  
  // Java风格的Base64解码表
  const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  const decodeMap = new Uint8Array(128);
  
  // 初始化解码表
  for (let i = 0; i < base64Chars.length; i++) {
    decodeMap[base64Chars.charCodeAt(i)] = i;
  }
  
  // 计算输出长度
  let outputLength = 0;
  for (let i = 0; i < normalizedBase64.length; i++) {
    const c = normalizedBase64.charCodeAt(i);
    if (c === 61) break; // '='
    if (c < 128 && decodeMap[c] !== 0 || c === base64Chars.charCodeAt(0)) {
      outputLength++;
    }
  }
  
  outputLength = Math.floor(outputLength * 3 / 4);
  
  // 创建输出数组
  const output = new Uint8Array(outputLength);
  
  // 解码过程
  let buffer = 0;
  let bitsInBuffer = 0;
  let outputIndex = 0;
  
  for (let i = 0; i < normalizedBase64.length; i++) {
    const c = normalizedBase64.charCodeAt(i);
    
    // 跳过非法字符
    if (c === 32 || c === 10 || c === 13 || c === 9) continue; // 空格、换行、回车、制表符
    
    // 遇到填充字符则停止
    if (c === 61) break; // '='
    
    // 获取解码值
    let value;
    if (c < 128) {
      value = decodeMap[c];
    } else {
      value = 0; // 非法字符
    }
    
    // 累积位
    buffer = (buffer << 6) | value;
    bitsInBuffer += 6;
    
    // 当累积了足够的位时，输出字节
    if (bitsInBuffer >= 8) {
      bitsInBuffer -= 8;
      output[outputIndex++] = (buffer >> bitsInBuffer) & 0xFF;
    }
  }
  
  return output;
}

/**
 * 将JavaScript的无符号字节转换为Java风格的有符号字节
 * @param {number} unsignedByte - 无符号字节值 (0-255)
 * @returns {number} - 有符号字节值 (-128到127)
 */
export function toSignedByte(unsignedByte) {
  return unsignedByte > 127 ? unsignedByte - 256 : unsignedByte;
}

/**
 * 验证JavaScript与Java的Base64解码结果是否一致
 * @param {Uint8Array} jsBytes - JavaScript解码结果
 * @param {Array<number>} javaBytes - Java解码结果（有符号字节数组）
 * @returns {boolean} - 结果是否一致
 */
export function verifyResults(jsBytes, javaBytes) {
  if (jsBytes.length !== javaBytes.length) {
    console.log(`长度不匹配: JavaScript=${jsBytes.length}, Java=${javaBytes.length}`);
    return false;
  }
  
  let differences = 0;
  const maxDisplay = 10; // 最多显示10个差异
  
  for (let i = 0; i < jsBytes.length; i++) {
    // 将JavaScript的无符号字节转换为有符号字节进行比较
    const jsSignedByte = toSignedByte(jsBytes[i]);
    
    if (jsSignedByte !== javaBytes[i]) {
      differences++;
      if (differences <= maxDisplay) {
        console.log(`差异在位置 ${i}: JavaScript=${jsBytes[i]}, Java=${javaBytes[i]}`);
        console.log(`  JavaScript(有符号): ${jsSignedByte}`);
        console.log(`  十六进制: JavaScript=${(jsBytes[i] & 0xFF).toString(16).padStart(2, '0')}, Java=${(javaBytes[i] & 0xFF).toString(16).padStart(2, '0')}`);
      }
    }
  }
  
  if (differences > 0) {
    console.log(`总共发现 ${differences} 处差异`);
    return false;
  }
  
  return true;
}
